<?
require_once ('config.php');

function ff_sql_query ($query_text) {
        if (DEBUG)
                echo $query_text . PHP_EOL;
        $result_2 = mysql_query($query_text);
        if (!$result_2) {
                echo 'Invalid query: ' . mysql_error() . PHP_EOL;
        }
        return $result_2;
}

//$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
$mysqli_link = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) {
    printf("Не удалось подключиться: %s\n", mysqli_connect_error());
    exit();
}

//$db_selected = mysql_select_db(DB_NAME, $link);
//if (!$db_selected) {
//		die ('Не удалось выбрать базу foo: ' . mysql_error());
//}

$mysqli_link->query("SET NAMES 'utf8'");
if (($mysqli_link->affected_rows) === -1) {
	echo "Error at line " . __LINE__ . PHP_EOL . " Query: " . $sql_query . PHP_EOL;
}

//$sql_query = "SELECT id, privateid FROM " . DB_TABLE_CATALOG . " WHERE `has_descr` = 0 group by privateid limit 100";
$sql_query = "select * from (SELECT *,IF(strlen_descr > 0,strlen_descr, 0) as strlen_descr_int FROM "
."(select privateid, (select length(description) as strlen_descr from items_info where " . DB_TABLE_CATALOG_BASE . ".privateid = items_info.privateid) as strlen_descr, (select desc_fail_count from items_info where " . DB_TABLE_CATALOG_BASE . ".privateid = items_info.privateid) as desc_fail_count from " . DB_TABLE_CATALOG_BASE . " group by privateid)"
."  as T1 )as T2 where strlen_descr_int < 1 AND desc_fail_count < 10 limit 100";
$result = $mysqli_link->query($sql_query);
if (($mysqli_link->affected_rows) === -1) {
	echo "Error at line " . __LINE__ . PHP_EOL . " Query: " . $sql_query . PHP_EOL;
}

//$result = ff_sql_query ($sql_query);
if (($result->num_rows) >0) {
	//while ($sql_row = mysql_fetch_assoc($result)) {
	while ($sql_row = $result->fetch_assoc()) {
		if (1) {
			print_r($sql_row);
		}
		$start_time = MICROTIME(TRUE);
		$item_info = file ('http://toololdi.1ka.ru/oldi-site-parser/fetch_item_content_by_id.php?id=' . $sql_row['privateid']);
		$stop_time = MICROTIME(TRUE);
		$item_info = json_decode (iconv("UTF-8", "cp1251",$item_info[0]), TRUE);
		
		if ((json_last_error() === 0) AND ((count($item_info) === 2)) OR (isset($item_info['item_description']))) {
			if (DEBUG)
			{
				echo "ok";
			}
			$sql_query = 
			"INSERT INTO  `items_info` (`privateid` ,`description` ,`photo`) VALUES ('" . $sql_row['privateid'] . "',  '" .
			$mysqli_link->real_escape_string($item_info['item_description']) . "',  '" . $mysqli_link->real_escape_string(json_encode($item_info['photos'])) . "')" 
			. " ON DUPLICATE KEY UPDATE "
			. " `description` = '" . $mysqli_link->real_escape_string($item_info['item_description']) . "'"
			. ", `photo` = '" . $mysqli_link->real_escape_string(json_encode($item_info['photos'])) . "'"
			. " ";
			//$result_2 = ff_sql_query ($sql_query);
			
			$result_2 = $mysqli_link->query($sql_query);
			if (($mysqli_link->affected_rows) === -1) {
				echo "Error at line " . __LINE__ . PHP_EOL . " Query: " . $sql_query . PHP_EOL;
			}

			if ($result_2) {
			/*	$sql_query = 
				"UPDATE  `catalog` SET  `has_descr` =1 WHERE  `id` =  '" . $sql_row['id'] . "'";
				ff_sql_query ($sql_query);*/
				echo 'Updated ' . $sql_row['privateid'] . PHP_EOL;
			}
		}
		else {
				echo ('Shit happens. Line ' . __LINE__ . ". Private id " . $sql_row['privateid'] . PHP_EOL);
				echo ' ' . 'Count of item_info=' . count($item_info) . PHP_EOL;
				print_r ($item_info);
				$sql_query = 
				"INSERT INTO  `items_info` (`privateid`, `desc_fail_count`) VALUES ('" . $sql_row['privateid'] . "', '1') "
				. " ON DUPLICATE KEY UPDATE "
				. "`desc_fail_count` = `desc_fail_count` + 1 "
				. " ";
				$result_2 = $mysqli_link->query($sql_query);
				if (($mysqli_link->affected_rows) === -1) {
					echo "Error at line " . __LINE__ . PHP_EOL . " Query: " . $sql_query . PHP_EOL;	
				}
				else {
					echo "Fail count updated " . __LINE__ . PHP_EOL /* . " Query: " . $sql_query . PHP_EOL*/;	
				}
			}
		$time = $stop_time - $start_time;
		echo " I got OLDI page for " . $time . " seconds" . PHP_EOL;
		if ($time >10) {
			sleep (10);
		}
		elseif (($time <5) AND ($time > 1)) {
			sleep (1);
		}
		else {
			sleep ($time);
		}
	}
}
else {
	if (DEBUG) {
		echo 'Notice: no unprocessed recoreds' . PHP_EOL;
	}
	die ('');
}

$mysqli_link->close();


?>
